package org.apache.http.a;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import org.apache.http.HttpEntity;
import org.apache.http.d;
import org.apache.http.entity.b;
import org.apache.http.protocol.a;

public final class e {
    public static String a(HttpEntity httpEntity) throws IOException, d {
        return a(httpEntity, (Charset) null);
    }

    public static String a(HttpEntity httpEntity, Charset charset) throws IOException, d {
        String dVar;
        Charset charset2 = null;
        boolean z = false;
        a.a((Object) httpEntity, "Entity");
        InputStream content = httpEntity.getContent();
        if (content != null) {
            int contentLength;
            try {
                if (httpEntity.getContentLength() <= 2147483647L) {
                    z = true;
                }
                a.a(z, "HTTP entity too large to be buffered in memory");
                contentLength = (int) httpEntity.getContentLength();
                if (contentLength < 0) {
                    contentLength = 4096;
                }
                b a = b.a(httpEntity);
                if (a != null) {
                    charset2 = a.b();
                }
            } catch (UnsupportedCharsetException e) {
                if (charset == null) {
                    throw new UnsupportedEncodingException(e.getMessage());
                }
            } catch (Throwable th) {
                content.close();
            }
            if (charset2 == null) {
                charset2 = charset;
            }
            if (charset2 == null) {
                charset2 = a.a;
            }
            Reader inputStreamReader = new InputStreamReader(content, charset2);
            d dVar2 = new d(contentLength);
            char[] cArr = new char[1024];
            while (true) {
                int read = inputStreamReader.read(cArr);
                if (read == -1) {
                    break;
                }
                dVar2.a(cArr, 0, read);
            }
            dVar = dVar2.toString();
            content.close();
        }
        return dVar;
    }
}
